package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.constant.TokenConstant;
import com.itheima.dto.AddEmployeeDto;
import com.itheima.dto.LoginDto;
import com.itheima.pojo.Employee;
import com.itheima.result.R;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/login")
    public R<EmployeeVo> login(@RequestBody LoginDto dto) {
        String password = dto.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        Employee employee = employeeService.getEmployeeByUsernameAndPassword(dto.getUsername(), password);
        if (employee == null) {
            return R.error("员工用户名或密码不正确");
        }

        // 步骤五：生成token，Token为当前登录用户的身份凭证，后续前端每次请求其他接口时，需要带上token证明已完成登录
        // Token需要具备两个条件
        // 1. 不能重复
        // 2. 通过token，可以找到用户的身份信息
        // 3. 需要加密
        // 所以这里用 MD5(时间戳 + 当前用户id) 的方式生成
        String token = "" + System.currentTimeMillis() + employee.getId();
        token = DigestUtils.md5DigestAsHex(token.getBytes(StandardCharsets.UTF_8));

        redisTemplate.opsForValue().set(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token, JSON.toJSONString(employee), 2, TimeUnit.HOURS);
        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtils.copyProperties(employee, employeeVo);
        employeeVo.setToken(token);
        return R.success(employeeVo);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        redisTemplate.delete(token);
        return R.success("登出成功");
    }

    @PostMapping
    public R<String> addEmployee(@RequestBody AddEmployeeDto dto, HttpServletRequest request) throws IOException {
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        String token = request.getHeader("Authorization");
        String auditEmpStr = (String) redisTemplate.opsForValue().get(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token);
        Employee auditEmp = JSON.parseObject(auditEmpStr, Employee.class);
        if (auditEmp == null) {
            return R.error("NOTLOGIN");
        }
        Long auditEmpId = auditEmp.getId();
        employee.setCreateUser(auditEmpId);
        employee.setUpdateUser(auditEmpId);
        employeeService.addEmployee(employee);

        return R.success("新增员工成功");
    }

    @GetMapping("/page")
    public R<Page> page(HttpServletRequest request,
                        @RequestParam(value = "page", defaultValue = "0") int page,
                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                        @RequestParam(required = false) String name) {


        Page<Employee> pageInfo = employeeService.getPage(page, pageSize, name);
        return R.success(pageInfo);
    }
}
